package mallindex

import (
	"context"
	// "fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/rpc/backendclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/product/rpc/productclient"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetWaterfallGoodsListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetWaterfallGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWaterfallGoodsListLogic {
	return &GetWaterfallGoodsListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetWaterfallGoodsListLogic) GetWaterfallGoodsList(
	req *types.GetWaterfallGoodsListReq,
	headers *[]*types.Header,
) (resp *types.SectionGoodsListResp, err error) {
	userId := jwt.GetUserId(l.ctx)

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	preload := "sectionProduct:SectionId,ProductId"
	preFilterEntity := "section"
	var preFilters []string
	preFilters = append(preFilters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	preFilters = append(preFilters, "Type,equalTo:"+strconv.FormatInt(int64(globalkey.SettingSectionTypeWaterfallIndex), 10))
	res, err := l.svcCtx.BackendRpc.GetSectionProductList(l.ctx, &backendclient.BaseListReq{
		Offset:          uint32((page - 1) * pageSize),
		Limit:           uint32(pageSize),
		Preload:         pointy.GetPointer(preload),
		PreFilterEntity: pointy.GetPointer(preFilterEntity),
		PreFilter:       pointy.GetPointer(strings.Join(preFilters, ";")),
		VisitorId:       pointy.GetPointer(userId),
		PlatformId:      pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.SectionGoodsListResp{
		BaseListInfo: types.BaseListInfo{
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(res.List) > 0 {
		var pids []string
		productIdMap := make(map[uint64]struct{})
		for _, v := range res.List {
			if v.ProductId != nil && *v.ProductId > 0 {
				pid := *v.ProductId
				if _, ok := productIdMap[pid]; !ok {
					pids = append(pids, strconv.FormatInt(int64(pid), 10))
					productIdMap[pid] = struct{}{}
				}
			}
		}

		if len(pids) > 0 {
			products, err := l.getProductListByIds(strings.Join(pids, ","))
			if err != nil {
				return nil, err
			}

			if len(products) > 0 {
				idProductMap := make(map[uint64]*types.GoodsInfo)
				for _, product := range products {
					if product.Id != nil && *product.Id > 0 {
						idProductMap[*product.Id] = product
					}
				}

				for _, v := range res.List {
					if v.ProductId != nil && *v.ProductId > 0 {
						if goods, ok := idProductMap[*v.ProductId]; ok {
							resp.List = append(resp.List, &types.SectionGoodsInfo{
								GoodsInfo: goods,
							})
						}
					}
				}
			}
		}

		*headers = []*types.Header{
			{
				Key:   "x-class",
				Value: "com.djx.appview.MallIndexPage",
			},
		}
	}

	return resp, nil
}

func (l *GetWaterfallGoodsListLogic) getProductListByIds(ids string) (resp []*types.GoodsInfo, err error) {
	preload := "product:Id,Title,Slug"
	eagerLoad := "product:productMeta,productMedia"
	preload += ";productMeta:mediaId,mediaUrl,retailPriceMin"
	preload += ";productMedia:Uid,Url"

	var filters []string
	filters = append(filters, "virtual,equalTo:"+strconv.FormatInt(int64(globalkey.ProductTypePhysical), 10))
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	filters = append(filters, "Id,in:"+ids)

	res, err := l.svcCtx.ProductRpc.GetProductList(l.ctx, &productclient.BaseListReq{
		Preload:   pointy.GetPointer(preload),
		EagerLoad: pointy.GetPointer(eagerLoad),
		Filter:    pointy.GetPointer(strings.Join(filters, ";")),
	})
	if err != nil {
		return nil, err
	}

	if len(res.List) > 0 {
		for _, v := range res.List {
			// logrus.Info(fmt.Sprintf("GetLiveTileList getProductListByIds GetProductList res.List: %+v", v))
			var retailPriceMin *string
			var mediaUrl *string
			if len(v.Meta) > 0 {
				for _, m := range v.Meta {
					if m.Key == nil || m.Value == nil {
						continue
					}

					val := *m.Value
					switch *m.Key {
					case "retailPriceMin":
						retailPriceMin = pointy.GetPointer(val)
					case "mediaUrl":
						mediaUrl = pointy.GetPointer(val)
					}
				}
			}

			if len(v.Media) > 0 {
				for _, m := range v.Media {
					if mediaUrl != nil {
						break
					}

					var url string
					if m.Url != nil && len(*m.Url) > 0 {
						url = *m.Url
					}
					if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
						url = *m.Uri
					}
					mediaUrl = pointy.GetPointer(url)
				}
			}

			resp = append(resp, &types.GoodsInfo{
				Id:       v.Id,
				Title:    v.Title,
				Slug:     v.Slug,
				MinPrice: retailPriceMin,
				ImageUrl: mediaUrl,
			})
		}
	}

	return resp, nil
}
